/**
 * 事件分发类
 * @author zhouzhanglin
 */
EventDispatcher = function()
{
	this._eventArray = []; //对当前类的侦听 事件
	this.name="";
	this.className="EventDispatcher";
};
/**
 * 输出
 */
EventDispatcher.prototype.toString = function()
{
	return "type:"+this.className+" - name:"+this.name;	
};
/**
 * 添加侦听
 * @param type 事件类型
 * @param listener 添加函数
 */
EventDispatcher.prototype.addEventListener = function(type, listener )
{
	if(this._eventArray[type])
	{
		this._eventArray[type].push(listener);
	}else{
		this._eventArray[type]= [listener];
	}
};
/**
 * 移除侦听
 * @param type 事件类型
 * @param listener 添加函数
 */
EventDispatcher.prototype.removeEventListener = function(type,listener)
{
	var listeners =  this._eventArray[type] ;
	if( listeners )
	{
		var i = 0;
		var LEN = listeners.length ;
		for(i ; i<LEN ; ++i )
		{
			if(listeners[i]==listener)
			{
				listeners.splice(i,1);
				if(listeners.length==0){
					delete 	this._eventArray[type] ;
				}
				break;	
			}
		}
	}
};
/**
 * 抛出事件
 * @param event
 */
EventDispatcher.prototype.dispatchEvent = function(event)
{
	var listeners = this._eventArray[event._type] ;
	if ( !listeners && !event._bubbles) return; // 不需要做任何事
	 
	var previousTarget = event._target;
	if (previousTarget == null || event._currentTarget != null) event._target = this ;
	 
	var stopImmediatePropagation = false;
	if (listeners != null && listeners.length> 0)
    {
          event._currentTarget = this ;
          var LEN = listeners.length ;
          var listener ;
  		  for(var i=0 ; i<LEN ;++i)
  		  {
  			    listener = listeners[i] ;
  			    listener(event);
	  			if (event._stopsImmediatePropagation)
	            {
	                stopImmediatePropagation = true;
	                break;
	            }
  		  }
    }

	if (!stopImmediatePropagation && event._bubbles && !event._stopsPropagation && this instanceof DisplayObject )
	{
	       if (this._parent != null)
	       {
	           event._currentTarget = null ; 
	           this._parent.dispatchEvent(event);
	       }
	}
		  
	if (previousTarget)  event._target = previousTarget ;
};

/**
 * 判断是否有侦听
 * @param type 事件类型
 */
EventDispatcher.prototype.hasEventListener = function(type)
{
	return this._eventArray[type]!=undefined && this._eventArray[type]!=null ;
};



//==============私有方法==============================
/**
 * 释放资源
 */
EventDispatcher.prototype.dispose = function()
{
	for ( var type in  this._eventArray)
	{
		var i = 0;
		var LEN = this._eventArray[type].length ;
		for(i ; i<LEN ; ++i )
		{
			this._eventArray[type][i] = null ;
		};
		delete this._eventArray[type];
	}
	this._eventArray=[];
};